package com.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.ListIterator;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.dao.*;

public class HomeServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4827014212728524042L;

	private Logger logger = Logger.getLogger(this.getClass());
	private RequestDispatcher homeJsp;

	@Override
	public void init(ServletConfig config) throws ServletException {
		ServletContext context = config.getServletContext();
		homeJsp = context.getRequestDispatcher("/home.jsp");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
				 
		String id = req.getParameter("id");
		String name = id;
		String firstName="";
		String lastName="";
		
		if (id != "" && id != null) {
			int ID = Integer.parseInt(id);
			UserHome userDao = new UserHome();
			User user = userDao.findById(new Integer(ID));
			//name = user.getUsername();
			try {
				Account searchAcc = new Account();
				AccountHome accDao = new AccountHome();
				searchAcc.setUser(user);
				List li = accDao.findByUser(user);
				ListIterator it = li.listIterator();
				
				while(it.hasNext()) {
					Account a = (Account)it.next();
					firstName = "First Name: " + a.getFirstname().toUpperCase();
					lastName = "Last Name: " + a.getLastname();
					name = user.getUsername();
				}

			} catch (Exception e) {
				System.out.println(e.toString());
				name = user.getUsername();
			}

		}
		  
/*		PrintWriter writer = resp.getWriter();
		writer.println("<html><body>");
		writer.print("<h1>hi ");
		writer.print(name);
		writer.print("</h2>");
		writer.println("</html></body>");*/

		logger.debug("HomeServlet.doGet()");
		req.setAttribute("username",name);
		req.setAttribute("firstname",firstName);
		req.setAttribute("lastname",lastName);
		homeJsp.forward(req, resp);
	}

}
